
package com.example.timeskilltest.util;

import java.util.concurrent.TimeUnit;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;

/**
 * redis 操作工具
 *
 * @author mei.xiaoliang@qq.com
 */
@Configuration
public class RedisUtil {

    private final Logger        logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    /**
     * 放值
     */
    public void set(String key, String value) {
        ValueOperations<String, String> ops = stringRedisTemplate.opsForValue();
        try {
            ops.set(key, value);
            logger.debug("redis 放值 key: {}, value: {}", key, value);
        } catch (Exception ignored) {
        }
    }

    /**
     * 放值（含有效期）, 过期时间：秒
     */
    public void set(String key, String value, long timeout) {
        ValueOperations<String, String> ops = stringRedisTemplate.opsForValue();
        try {
            ops.set(key, value, timeout, TimeUnit.SECONDS);
            logger.debug("redis 放值 key: {}, value: {}, timeout: {}", key, value, timeout);
        } catch (Exception ignored) {
        }
    }

    /**
     * 取值
     */
    public String get(String key) {
        ValueOperations<String, String> ops = stringRedisTemplate.opsForValue();
        try {
            String result = ops.get(key);
            Long expire = stringRedisTemplate.getExpire(key);
            logger.debug("redis 取值 key: {}, value: {}, expire: {}", key, result, expire);
            return result;
        } catch (Exception ignored) {
        }
        return "";
    }

}
